<?php

class FaxManager {
  
  static private $instance;
  
  private $hylafax_inbox_path;
  private $faxviewer_path;
  private $faxviewer_db_path;
  private $imagemagick_path;
  private $imagecache_path;
  
  function __construct() {
    $this->hylafax_inbox_path = FaxConfig::getConfig()->getValue('hylafax_inbox_path');
    $this->faxviewer_path = FaxConfig::getConfig()->getValue('faxviewer_path');
    $this->faxviewer_db_path = FaxConfig::getConfig()->getValue('faxviewer_db_path');
    $this->imagemagick_path = FaxConfig::getConfig()->getValue('imagemagick_path');
    $this->imagecache_path = FaxConfig::getConfig()->getValue('imagecache_path');
  }
  
  public static function getInstance() {
    if(!self::$instance instanceof self){
      self::$instance = new self;
    }
    return self::$instance;
  }
  
  public static function getFaxUrl($id) {
    return FaxConfig::getConfig()->getValue('hylafax_inbox_path').$id.".tif";
  }
  
  public static function getFaxId($filename) {
    $parts = explode(".tif", $filename);
    return $parts[0];
  }
  
  public static function convertFilenamesToIDs(&$item, $key) {
    $parts = explode(".tif", $item);
    $item = $parts[0];
  }
  
  public static function filterFaxFiles($filename) {
    return preg_match("/.*\.tif$/", $filename);
  }
  
  // Deprecated
  public static function filterNewFaxFiles($filename) {
    return preg_match("/.*\.tif$/", $filename);
  }
  
  
  public function trash($id) {
    $db = new PDO("sqlite:".$this->faxviewer_db_path);
    $db->query("UPDATE recvq SET softfolder = 'trash' WHERE id = '".$id."'");
  }
  
  // Convierte el tiff a jpg. Por los momentos he visto dos tipos de Fax: Pixel
  // Aspect Ratio de aprox 0.5 y de aprox 1. Si es 0.5, duplico la resolución
  // vertical al convertir la imagen.
  // El filtro Lanczos genera imágenes más sharpen que el normal.
  // 
  // Converts the tiff to jpeg. It seems to be two types of fax tiff:
  // Pixel Aspect Ratio of aprox. 0.5 and aprox. 1. If the case is 0.5, we double
  // the vertical resolution when converting the image.
  //
  private function createImage($id, $path, $size, $par) {
    ($par < 0.6) ? $resize = "-resize x200%!" : $resize = "";
    exec($this->imagemagick_path.'convert "'.self::getFaxUrl($id).'" -colorspace RGB -filter Lanczos '.$resize.' -resize '.$size.' -density 72x72 "'.$path.$id.'-%d.jpg"');
  }
  
  // Con ImageMagick 6.4.2 no hace falta hacer resize, los pdfs salen perfectos
  // de una. Aqui lo arreglamos para que sea compatible con 6.0.7.
  // 
  // ImageMagick 6.4.2 creates perfect PDFs without having to take care of the aspect ratio.
  // This is for ImageMagick 6.0.7. (we need to take care of the PAR)
  //
  private function createPDF($id, $path, $par) {
    ($par < 0.6) ? $resize = "-resize x200%!" : $resize = "";
    exec($this->imagemagick_path.'convert "'.self::getFaxUrl($id).'" -colorspace RGB '.$resize.' -density 204x204 "'.$path.$id.'.pdf"');
  }
  
  // Devuelve un Array con el inbox según Sqlite
  // 
  // Returns an array with Sqlite's inbox
  //
  public function getInbox() {
    $db = new PDO("sqlite:".$this->faxviewer_db_path);
    $result = $db->query("SELECT * FROM recvq WHERE softfolder = 'inbox' ORDER BY id DESC");
    return $result->fetchAll();
  }
  
  
  // Devuelve un Array simplificado con los ids registrados en Sqlite en el 
  // softfolder indicado. Si se indica Softfolder "all", devulve todos.
  //
  // Returns a simple Array with the ids stored in Sqlite in a particular "softfolder".
  // When "all" all id's are returned.
  // 
  public function getRegisteredIDs($softfolder) {
    if ($softfolder == "all") {
      $query = "SELECT id FROM recvq";
    } else {
      $query = "SELECT id FROM recvq WHERE softfolder = '".$softfolder."'";
    }
    
    $db = new PDO("sqlite:".$this->faxviewer_db_path);
    $result = $db->query($query);
    $result_array = $result->fetchAll();
    array_walk(&$result_array, array(&$this, "simplifyResults"));
    return $result_array;
  }
  
  private function simplifyResults(&$item, $key){
    $item = $item['id'];
  }
  
  public function getFax($id) {
    $db = new PDO("sqlite:".$this->faxviewer_db_path);
    $result = $db->query("SELECT * FROM recvq WHERE id = '".$id."'");
    // TODO: No hace falta hacer el reverse aquí!!!! es sólo un registro.
    return array_reverse($result->fetchAll());
  }
  
  
  public function checkInbox() {
    $inbox_new_ids = $this->getNewFaxIDs();
    if (count($inbox_new_ids) > 0){
      $this->registerNewFaxes($inbox_new_ids);
    }
    return true;
  }
  
  public function registerNewFaxes($newIDs) {
    $db = new PDO("sqlite:".$this->faxviewer_db_path);
    foreach ($newIDs as $newID) {
      $fax_obj = new Fax($newID);
      $db->query("INSERT INTO recvq values('".$fax_obj->id."', '".$fax_obj->pages."', '".$fax_obj->par."', 'inbox', '".$fax_obj->telf."', '".$fax_obj->ts."')");
      $this->createImage($fax_obj->id, $this->imagecache_path."recvq/thumbnails/", "185", $fax_obj->par);
      $this->createImage($fax_obj->id, $this->imagecache_path."recvq/medium/", "730", $fax_obj->par);
      $this->createPDF($fax_obj->id, $this->imagecache_path."recvq/pdf/", $fax_obj->par);
    }
  }
  
  public function getNewFaxIDs() {
    $inbox_contents_ids = array_filter(scandir($this->hylafax_inbox_path), array(&$this, "filterFaxFiles"));
    array_walk(&$inbox_contents_ids, array("FaxManager", "convertFilenamesToIDs"));
    $inbox_registered_ids = $this->getRegisteredIDs("all");
    return array_diff($inbox_contents_ids, $inbox_registered_ids);
  }
  
}
?>